<script setup lang="ts">
import type { ColumnProperty } from "./type";
import { throttle } from ".";
const props = defineProps<{
  list: any[];
  columns: ColumnProperty[];
}>();

const options = reactive({
  height: 40,
  startInx: 0,
  endInx: 14,
});

const infoList = ref<any[]>([]);
const tbodyEl = useTemplateRef("tbody");
const phantomHeight = computed(() => props.list.length * 40 + "px");

onMounted(() => {
  scrollHandle();
});

function scrollHandle() {
  const scrool = tbodyEl.value!.scrollTop;
  options.startInx = Math.floor(scrool / options.height);
  options.endInx = options.startInx + 14;
  infoList.value = props.list.slice(options.startInx, options.endInx);
  // console.log("options", scrool, options, infoList.value, props.list);
}
// 创建节流函数
const throttledScroll = throttle(scrollHandle);
</script>
<template>
  <div class="time_slicing">
    <div class="thead">
      <div class="td index">序号</div>
      <div class="td" v-for="th in columns" :key="th.prop">{{ th.lab }}</div>
    </div>
    <div class="tbody" ref="tbody" @scroll="throttledScroll">
      <div class="phantom"></div>
      <div class="lists">
        <div class="tr" v-for="(li, inx) in infoList" :key="li.id">
          <div class="td index">{{ li.id }}</div>
          <div class="td" v-for="tr in columns" :key="tr.prop">
            {{ li[tr.prop] }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.time_slicing {
  display: flex;
  flex-direction: column;
  width: 1000px;
  height: 600px;
  color: #333;
  border: 1px solid pink;
  border-radius: 4px;

  .thead {
    display: flex;
    padding: 0 12px;
    background-color: #ededed;
    .td {
      font-weight: 600;
    }
  }
  .td {
    flex: 4;
    height: 40px;
    font-size: 16px;
    line-height: 40px;
    &.index {
      flex: 1;
    }
    &:nth-child(2) {
      flex: 2;
    }
  }
  .tbody {
    flex: 1;
    position: relative;
    overflow-y: auto;
    .phantom {
      position: absolute;
      left: 0;
      width: 100%;
      height: v-bind(phantomHeight);
    }
    .lists {
      position: sticky;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      //   background-color: pink;
    }
    .tr {
      display: flex;
      align-items: center;
      height: 40px;
      padding: 0 12px;
      &:nth-child(odd) {
        background-color: #fafafa;
      }
    }
  }
}
</style>
